<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import Toast from './components/common/Toast.vue';
import { toast as toastService } from './services/toastService';
import { useUserStore } from './stores/userStore';
import { authAPI } from './services/api';

// 获取用户状态管理
const userStore = useUserStore();

// App级别的逻辑可以在这里添加

// 创建对Toast组件的引用
const toastRef = ref(null);

// 当组件挂载时
onMounted(async () => {
  // 注册toast监听器
  if (toastRef.value) {
    // 注册监听器，将消息转发到Toast组件
    toastService.registerListener('app', (type, message, duration) => {
      if (toastRef.value && toastRef.value.toast) {
        toastRef.value.toast[type](message, duration);
      }
    });
  }

  // 验证token有效性
  const token = localStorage.getItem('token');
  if (token) {
    try {
      console.log('验证令牌有效性...');
      const response = await authAPI.verifyToken();
      
      if (response && response.valid) {
        console.log('令牌有效，已验证用户身份');
        // 如果token有效但用户状态未设置，从localStorage恢复用户状态
        if (!userStore.isLoggedIn) {
          const userData = JSON.parse(localStorage.getItem('user'));
          if (userData) {
            userStore.loginUser(userData);
            console.log('已恢复用户会话状态');
          }
        }
      } else {
        console.log('令牌无效，清除登录状态');
        userStore.logoutUser();
      }
    } catch (error) {
      console.error('验证令牌失败:', error);
      userStore.logoutUser();
    }
  }
});

// 当组件卸载时，移除toast监听器
onUnmounted(() => {
  toastService.removeListener('app');
});
</script>

<template>
  <div class="app-container">
    <!-- 添加Toast组件 -->
    <Toast ref="toastRef" />
    
    <router-view v-slot="{ Component }">
      <transition name="fade" mode="out-in">
        <component :is="Component" />
      </transition>
    </router-view>
  </div>
</template>

<style>
/* 全局样式 */
body {
  @apply bg-gray-50 text-gray-900;
  font-family: 'Inter', system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.app-container {
  @apply w-full min-h-screen;
}

/* 页面过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
